//
//  BLinkRefreshHeader.swift
//  live
//
//  Created by melvyn on 2018/8/23.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit

class BLinkRefreshHeader: MJRefreshHeader {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView.init(image: UIImage(named: "livebase_common_pull_loading_1_165x50_"))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        var animationImages: [UIImage] = []
        for i in 1...4 {
            animationImages.append(UIImage(named: "livebase_common_pull_loading_\(i)_165x50_")!)
        }
        imageView.animationImages = animationImages
        imageView.animationDuration = 0.5
        imageView.animationRepeatCount = Int.max
        return imageView
    }()
    
    override func prepare() {
        super.prepare()
        
        mj_h = 50
        
        addSubview(imageView)
        
        NSLayoutConstraint.activate([
            imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
            imageView.centerXAnchor.constraint(equalTo: centerXAnchor)
            ])
    }
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard state == .refreshing else {
            return
        }
        imageView.stopAnimating()
        imageView.startAnimating()
    }
    
    override var state: MJRefreshState {
        didSet {
            switch state {
            case .idle:
                imageView.stopAnimating()
            case .refreshing:
                imageView.startAnimating()
            default:
                imageView.stopAnimating()
                break
            }
        }
    }
}
